﻿using System;
using QuickGraph;
using QuickGraph.Algorithms.RankedShortestPath;

namespace SystemWnioskujacy
{
    public class VariableDistance
    {
        BidirectionalGraph<QueryParameter, TaggedEdge<QueryParameter, int>> Graph = new BidirectionalGraph<QueryParameter, TaggedEdge<QueryParameter, int>>();

        public void Add(Query Q, int ID)
        {
            if (Q == null || Q.Length == 0) return;

            Graph.AddVertex(Q[0]);
            for (int i = 0, j = 1; j < Q.Length; i++, j++) Graph.AddVerticesAndEdge(new TaggedEdge<QueryParameter, int>(Q[i], Q[j], ID));
        }

        public bool Distance(QueryParameter Q1, QueryParameter Q2, out int D)
        {
            D = 0;
            var PathFinder = new HoffmanPavleyRankedShortestPathAlgorithm<QueryParameter, TaggedEdge<QueryParameter, int>>(Graph, E => 1.0);
            PathFinder.SetRootVertex(Q1);
            PathFinder.SetGoalVertex(Q2);
            PathFinder.Compute();

            if (PathFinder.ComputedShortestPathCount == 0)
            {
                PathFinder.SetRootVertex(Q2);
                PathFinder.SetGoalVertex(Q1);
                PathFinder.Compute();

                if (PathFinder.ComputedShortestPathCount == 0) return false;
                else
                {
                    if (!Array.Equals(Q1.Get(), Q2.Get()))
                    {
                        D = 0 - (PathFinder.ShortestPathCount - 1);
                        return true;
                    }
                    else return true;
                }
            }
            else
            {
                if (!Array.Equals(Q1.Get(), Q2.Get()))
                {
                    D = PathFinder.ShortestPathCount - 1;
                    return true;
                }
                else return true;
            }
        }
    }
}
